package service

import (
    "errors"
    "net/smtp"
    
    "github.com/jordan-wright/email"
    
    "collecter/app/common/helper"
)

type Email struct {
    ToUsers []string
    Subject string
    Format string  // 邮件内容格式：text、html
    Content string
    Annexs []string
}

func NewEmail() *Email {
    return &Email{}
}

func (e *Email)WithToUsers(toUsers []string) *Email {
    e.ToUsers = toUsers
    return e
}

func (e *Email)WithSbuject(sbuject string) *Email {
    e.Subject = sbuject
    return e
}

func (e *Email)WithFormat(format string) *Email {
    if len(format) == 0 {
        format = "text"
    }
    e.Format = format
    return e
}

func (e *Email)WithContent(content string) *Email {
    e.Content = content
    return e
}

func (e *Email)WithAnnexs(annexs []string) *Email {
    e.Annexs = annexs
    return e
}


//
// SendEmail
//  @Description: 发送邮件
//  @param toUsers 邮件接收者账号，可以同时发送多个
//  @param subject 邮件主题
//  @param content 邮件内容
//  @param annexs 邮件附件
//  @return error
//
func (e *Email) SendEmail() error {
    em := email.NewEmail()
    // 设置发送方的邮箱
    em.From = helper.Configer.GetString("email.fromUser")
    // 设置接收方的邮箱，可以同时设置多个
    em.To = e.ToUsers
    // 设置主题
    em.Subject = e.Subject
    // 设置邮件内容发送的内容
    if len(e.Format) == 0 {
        e.Format = "text"
    }
    if e.Format != "text" && e.Format != "html" {
        return errors.New("邮件内容格式参数错误")
    }
    if "text" == e.Format {
        em.Text = []byte(e.Content)
    } else {
        // 邮件内容是 html 页面，需要使用反引号（`）括起来
        em.HTML = []byte(e.Content)
    }
    
    // 添加邮件附件
    if len(e.Annexs) > 0 {
        for _, annex := range e.Annexs {
            if ok, err := helper.FileIsExists(annex); err != nil {
                helper.Logger.WithField("apart", "email_err").Error("发送邮件出错：" + err.Error())
                return err
            } else {
                if !ok {
                    helper.Logger.WithField("apart", "email_err").Error("发送邮件出错：邮件附件文件不存在")
                    return err
                }
                if _, err := em.AttachFile(annex); err != nil {
                    helper.Logger.WithField("apart", "email_err").Error("发送邮件出错：添加邮件附件出错")
                    return err
                }
            }
        }
    }
    // 设置服务器相关的配置
    auth := smtp.PlainAuth(
        "",
        helper.Configer.GetString("email.fromUser"),
        helper.Configer.GetString("email.authorizeCode"),
        helper.Configer.GetString("email.emailServer"))
    err := em.Send(helper.Configer.GetString("email.emailServer"), auth)
    // fmt.Printf("auth object: %+v\n", auth)
    // fmt.Printf("email object: %+v\n", em)
    if err != nil {
        helper.Logger.WithField("apart", "email_err").Error("发送邮件出错：" + err.Error())
    }
    return err
}